/*
 * share_mem.cpp
 *
 *  Created on: Feb 23, 2023
 *      Author: yglc
 */

#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include "share_mem.h"

unsigned int *g_map_sharemem;
int g_fd;

#define SHARE_MEM        0x20000000
#define SHARE_MEM_LEN    0x10000000    //32MB




int CShareMem_Init()
{

	g_map_sharemem = NULL;
	g_fd = -1;

	g_fd = open("/dev/mem", O_RDWR | O_SYNC);
    if (g_fd < 0) {
        printf("can not open /dev/mem \n");
        return (-1);
    }
    printf("/dev/mem is open \n");

    g_map_sharemem = (unsigned int*)mmap(NULL, SHARE_MEM_LEN, PROT_READ | PROT_WRITE, MAP_SHARED, g_fd, SHARE_MEM);
    if (g_map_sharemem == 0 ) {
        printf("NULL pointer\n");
    }
    else {
        printf("mmap successful\n");
    }

	return 0;
}

int CShareMem_Write_Byte(int addr,unsigned int value)
{
	unsigned int content;

	content = value;
	g_map_sharemem[addr] = content;


	return 0;
}

int CShareMem_Write(int addr,int size,unsigned char *buffer)
{

    if(size%4!=0)
    {
    	size = (size/4+1)*4;
    }

    memcpy(&g_map_sharemem[addr],buffer,size);

	return size;
}


unsigned int CShareMem_Read_Byte(int addr)
{
    unsigned int content;


    content = g_map_sharemem[addr];

	return content;
}

int CShareMem_Read(int addr,int size,unsigned char *buffer)
{

    if(size%4!=0)
    {
    	size = (size/4+1)*4;
    }

    memcpy(buffer,&g_map_sharemem[addr],size);

	return size;
}


int CShareMem_Close()
{

	close(g_fd);
	munmap(g_map_sharemem, SHARE_MEM_LEN);

	return 0;
}








